from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from .models import Product, Cart, CartItem

def product_list(request):
    products = Product.objects.all()
    paginator = Paginator(products, 3)  # 每页显示3个商品

    page_number = request.GET.get('page')  # 获取当前页码
    page_obj = paginator.get_page(page_number)  # 获取当前页的商品

    return render(request, 'shop/product_list.html', {'page_obj': page_obj})

def product_detail(request, product_id):
    product = Product.objects.get(id=product_id)
    return render(request, 'shop/product_detail.html', {'product': product})

@login_required
def add_to_cart(request, product_id):
    product = Product.objects.get(id=product_id)
    cart, created = Cart.objects.get_or_create(user=request.user)

    # 检查购物车中是否已存在该商品
    cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)

    if not created:
        cart_item.quantity += 1  # 如果已存在，增加数量
    cart_item.save()

    return redirect('cart_view')  # 重定向到购物车视图

@login_required
def cart_view(request):
    cart = Cart.objects.get(user=request.user)
    return render(request, 'shop/cart.html', {'cart': cart})

def add_products(request):
    if request.method == 'POST':
        Product.objects.create(
            name=request.POST['name'],
            description=request.POST['description'],
            price=request.POST['price'],
            stock=request.POST['stock'],
            category=request.POST['category'],
            brand=request.POST['brand'],
            image=request.FILES.get('image')
        )
        return redirect('product_list')

    return render(request, 'shop/add_product.html')

@login_required
def manage_products(request):
    products = Product.objects.all()
    return render(request, 'shop/manage_products.html', {'products': products})

@login_required
def edit_product(request, product_id):
    product = Product.objects.get(id=product_id)
    if request.method == 'POST':
        product.name = request.POST['name']
        product.description = request.POST['description']
        product.price = request.POST['price']
        product.stock = request.POST['stock']
        product.category = request.POST['category']
        product.brand = request.POST['brand']
        if 'image' in request.FILES:
            product.image = request.FILES['image']
        product.save()
        return redirect('manage_products')
    return render(request, 'shop/edit_product.html', {'product': product})

@login_required
def delete_product(request, product_id):
    product = Product.objects.get(id=product_id)
    product.delete()
    return redirect('manage_products')
